/**
 * 
 */
package com.shy.plugin.seo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.alibaba.fastjson.JSONObject;
import com.shy.base.util.StringUtils;
import com.shy.cms.entity.Site;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;

/**
 * <p>Title:ShenMaPost
 * <p>Description:神马平台mip提交接口，优先移动端，而没有移动端时才提交pc
 * @author H2013788
 * @date 2019年8月30日
 */
public class ShenMaPost {

	private static String smApiUrl = "https://data.zhanzhang.sm.cn/push?site={}&user_name={}&resource_name=mip_add&token={}"; //从百度站长平台获取
	
    //返回状态码
    private final static int SUCESS_200 = 200;
    private final static int ERROR_400 = 400;
    private final static int ERROR_201 = 201;
    private final static int ERROR_202 = 202;
    private final static int ERROR_500 = 500;
 
 
    /**
     * baidu post
     * @param urls  链接列表
     * @param params 参数
     * @return
     * @throws IOException   
     * @date: 2020年3月4日 下午9:37:14
     */
    public static String postUrl(List<String> urls, Map<String, Object> params) throws IOException {
		Set<String> set = new HashSet<String>(urls);
		urls = new ArrayList<String>(set);
		Site site = (Site) params.get("site");
		String result = "";
		if (StringUtils.isNotEmpty(site.getmBaseUrl())) {
			// 有移动端时只提交移动端
			List<String> mList = new ArrayList<String>();
			for (String url : urls) {
				if (url.indexOf(site.getmBaseUrl()) >= 0) {
					mList.add(url);
				}
			}
			if(!mList.isEmpty()) {
				params.put("urlType", "m");
				result += "【m提交】：" + postUrlByUrlType(mList, params);
			}
		} else {
			params.put("urlType", "pc");
			result += postUrlByUrlType(urls, params);
		}
		return result;
    }
    
    
    /**
     * baidu post
     * @param urls  链接列表
     * @param params 参数
     * @return
     * @throws IOException   
     * @date: 2020年3月4日 下午9:37:14
     */
    public static String postUrlByUrlType(List<String> urls, Map<String, Object> params) throws IOException {
        Set<String> set = new HashSet<String>(urls);
        urls = new ArrayList<String>(set);
        URLConnection urlConnection;
        StringBuffer result = new StringBuffer();
        PrintWriter postPrintWriter = null;
        BufferedReader bufferedReader = null;
        int statusCode;
        try {
        	Site site = (Site) params.get("site");
        	String domain = site.getDomain();
        	if(StringUtils.isNotEmpty(site.getmBaseUrl())) {
        	    domain = new URL(site.getmBaseUrl()).getHost();
        	}
        	String url = StrUtil.format(smApiUrl, domain, site.getSmName(), site.getSmToken());
            urlConnection = new URL(url.toString()).openConnection();
            urlConnection.setRequestProperty("Content-Type", "text/plain");
            urlConnection.setRequestProperty("User-Agent", "curl/7.12.1");
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
            postPrintWriter = new PrintWriter(httpUrlConnection.getOutputStream());
            //构造请求参数
            StringBuffer parm = new StringBuffer();
            for (String s : urls) {
                if (StringUtils.isNotEmpty(s)) {
                    //去除两头空格
                    String tmpUrl = s.trim();
                    if (tmpUrl.contains("http://") || tmpUrl.contains("https://")) {
                        parm.append(tmpUrl);
                        parm.append("\n");
                    }
                }
            }
            //发送参数
            postPrintWriter.print(parm);
            //刷新输出流缓冲
            postPrintWriter.flush();
            statusCode = httpUrlConnection.getResponseCode();
            switch (statusCode) {
                case SUCESS_200:
                    if (statusCode == SUCESS_200) {
                        //通过BufferedReader输入流来读取Url的响应
                        bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                        String line;
                        while ((line = bufferedReader.readLine()) != null) {
                            result.append(line);
                        }
                    }
                    String resultT = result.toString();
                    if (result != null) {
                        JSONObject jsonObject = JSONObject.parseObject(resultT);
                        Object t = jsonObject.get("not_same_site");
                        if (t != null) {
                            result.append("接口调用地址与提交的网址不匹配");
                        }
                    }
 
                    break;
                case ERROR_400:
                    result.append("请求参数有误");
                    break;
                case ERROR_201:
                    result.append("token错误");
                    break;
                case ERROR_202:
                    result.append("当日流量已用完");
                    break;
                case ERROR_500:
                    result.append("服务器内部错误");
                    break;
 
                default:
                    result.append("未知错误");
                    break;
            }
 
        } catch (Exception e) {
            e.printStackTrace();
            result.append("请求失败");
        } finally {
            //关闭流
            if (postPrintWriter != null) {
                postPrintWriter.close();
            }
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        }
        return result.toString();
    }
}
